package com.cxs.config.interceptor;

import com.cxs.entity.User;
import com.cxs.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

public class LastloginInterceptor implements HandlerInterceptor {

    @Autowired
    IUserService userService;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        if (true) {
            return;
        }
        String uri = request.getRequestURI();
        if (uri.equals("/login") || uri.equals("/logout") || uri.equals("/captcha")) {
            return;
        }

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || auth instanceof AnonymousAuthenticationToken || !auth.isAuthenticated()) {
            return;
        }
        // 更新当前用户的最后登陆时间
        User user = userService.getByUsername((String) auth.getPrincipal());
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setLastLogin(LocalDateTime.now());
        userService.updateUserById(updateUser);
    }
}
